﻿using System.Collections.Generic;
using UnityEngine;

namespace Assets
{
    class SquareMap
    {
        public Square[,] Squares;
        public readonly List<Vector3> verts;
        public readonly List<ushort> tris;
        float isoValue;

        public SquareMap(int mapSize, float gridScale, float isoValue)
        {
            Squares = new Square[mapSize, mapSize];
            verts = new List<Vector3>();
            tris = new List<ushort>();
            this.isoValue = isoValue;
            for (int x = 0; x < Squares.GetLength(0); x++)
            {
                for (int y = 0; y < Squares.GetLength(1); y++)
                {
                    float offset = mapSize * gridScale * 0.5f - gridScale * 0.5f;
                    var pos = new Vector2(x, y) * gridScale - new Vector2(offset, offset);
                    Squares[x, y] = new Square(pos, gridScale);
                }
            }
        }
        public void Update(float[,] girds)
        {
            verts.Clear();
            tris.Clear();
            for (int x = 0; x < Squares.GetLength(0); x++)
            {
                for (int y = 0; y < Squares.GetLength(1); y++)
                {
                    Square square = Squares[x, y];
                    square.Tr(isoValue, girds[x, y + 1], girds[x + 1, y + 1], girds[x, y], girds[x + 1, y]);

                    int index = this.verts.Count;
                    var verts = square.vertices;
                    var tris = square.triangles;
                    for (int i = 0; i < verts.Count; i++)
                    {
                        this.verts.Add(verts[i] + (Vector3)square.position);
                    }
                    for (int i = 0; i < tris.Count; i++)
                    {
                        this.tris.Add((ushort)(tris[i] + index));
                    }
                }
            }
        }
    }
}
